const Controller = require('egg').Controller;


class complaint extends Controller {
    /**
     * 菜单跳转
     * @returns {Promise<void>}
     */
    async to(){
        const {app,ctx,service} = this;
        await ctx.render('/admin/complaint_query.ejs',{});
    }

    /**
     * 跳转编辑页面
     * @returns {Promise<void>}
     */
    async toedit(){
        const {app,ctx,service} = this;
        //编辑id
        let id = ctx.request.query.id;
        await ctx.render('/admin/complaint_edit.ejs',{id:id});
    }

    /**
     * 跳转详情页面
     * @returns {Promise<void>}
     */
    async todetail(){
        const {app,ctx,service} = this;
        //编辑id
        let id = ctx.request.query.id;
        await ctx.render('/admin/complaint_detail.ejs',{id:id});
    }

    /**
     * 查询接口
     * isPage 是否分页
     * limit offset 每页限制数 偏移量
     * search 搜索项
     * /admin/接口
     * type get
     * @returns {Promise<void>}
     */
    async index(){
        const {app,ctx,service} = this;
        //取get请求参数
        let param = ctx.query;
        //初始化变量 用于请求参数中缺失部分参数时不至于导致报错
        let limit = 10;
        let offset = 0;
        let search = '%%';
        let isPage = 'true';

        //循环请求参数 赋值 到变量
        app.lodash.forEach(param,(v,k)=>{
            switch (k) {
                case 'pageSize':
                    limit = parseInt(v);break;
                case 'limit':
                    limit = parseInt(v);break;
                case 'page':
                    offset = parseInt((v - 1) * limit);break;
                case 'search':
                    search = v;break;
                case 'isPage':
                   isPage = v;break;
            }
        })

        let where_sql = ``;
        if(!app.lodash.isEmpty(search)){
            where_sql = ` and a.number like '%${search}%' `;
        }
        let sql = `
            select a.number,a.id,b.realname,b.province,b.address,b.phone,a.complaint,a.is_complaint
            from fd_order a
            left join fd_address b on a.address_id = b.id
            where a.deleted = '0' and a.is_complaint in('1') ${where_sql}
            order by a.is_complaint desc,a.created_at desc
        `;
        let count_sql = `
            select count(*) as total
            from fd_order a
            where a.deleted = '0' and a.is_complaint in('1') ${where_sql}
        `;

        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        let count = await ctx.model.query(count_sql,sequelize_query_param);

        //返回
        ctx.body = {
            code : 0,
            data,
            count:count[0].total,
            msg : ''
        }
    }

    /**
     * 单个记录查询接口
     * /admin/接口/:id
     * type : get
     * @returns {Promise<void>}
     */
    async show(){
        const {app,ctx,service} = this;
        //获取url请求参数
        let param = ctx.params;

        //创建规则
        const rule = {
            id:'required'
        };
        //验证
        const err = await app.validator.validate(param,rule);
        //判断验证结果
        if(!app.lodash.isEmpty(err)){
            //抛出验证错误信息
            ctx.throw(401,err[0].field+' -- '+err[0].message);
        }

        let order = await ctx.model.FdOrder.findOne({where:{id:param.id}})

        //判断处理是否成功
        if(app.lodash.isEmpty(order)){
            //失败 抛出错误信息
            ctx.throw(501,'记录查询失败');
        }

        //返回
        ctx.body = {
            code : 200,
            data : order,
            msg : ''
        }
    }

    /**
     * 更新接口
     * /admin/接口/:id
     * type put
     * @returns {Promise<void>}
     */
    async update(){
        const {app,ctx,service} = this;
        //获取post请求参数
        let param = ctx.request.body.data;
        //获取url请求参数
        param.id = ctx.params.id;

        //创建规则
        const rule = {
            id:'required',
            replay:'required',
        };
        //验证
        const err = await app.validator.validate(param,rule);
        //判断验证结果
        if(!app.lodash.isEmpty(err)){
            //抛出验证错误信息
            ctx.throw(401,err[0].field+' -- '+err[0].message);
        }

        let t = await ctx.model.transaction();
        try{
            let order = await ctx.model.FdOrder.findOne({where:{id:param.id},transaction:t,lock:t.LOCK.UPDATE});
            order.replay= param.replay,
                order.is_complaint = '2',
                order.replay_pic = param.pics.join(',');
            await order.save({transaction:t});
            t.commit();
        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }

        //返回
        ctx.body = {
            code : 200,
            data : {},
            msg : ''
        }
    }
}

module.exports = complaint;
